<template>
  <uv-popup ref="popupRef" mode="center" round="8" closeable @change="e=> emit('update:show', e.show)">
    <view class="popup">
      <view class="text-center text-16 py-12">
        <text v-if="form.id">编辑地址</text>
        <text v-else>添加地址</text>
      </view>

      <scroll-view scroll-y style="max-height: 50vh; ">
        <uv-form ref="formRef" label-position="left" :model="form" :rules="rules" label-width="60">
          <uv-form-item label="姓名" prop="name" border-bottom required>
            <uv-input v-model="form.name" placeholder="请输入收货人姓名" />
          </uv-form-item>
          <uv-form-item label="手机" prop="phone" border-bottom required>
            <uv-input v-model="form.phone" maxlength="11" type="number" placeholder="请输入手机号码" />
          </uv-form-item>
          <uv-form-item label="省市区" prop="province_name" border-bottom required @click="updateAreaShow(true)">
            <view class="relative w-full">
              <uv-input :model-value="`${form.province_name}${form.city_name}${form.district_name}`" placeholder="请选择省市区" readonly />
              <view class="absolute-full" />
            </view>
          </uv-form-item>
          <uv-form-item label="地址" prop="address" border-bottom required>
            <uv-textarea v-model="form.address" placeholder="请输入详细地址" height="40" />
          </uv-form-item>

          <uv-form-item label="默认" prop="is_def" border-bottom>
            <view class="flex-a">
              <uv-switch
                v-model="form.is_def"
                size="24"
                :active-value="1"
                :inactive-value="0"
                @change="value=> form.is_def = value"
              />
              <text class="text-12 pl-10 text-tips">设置默认地址状态</text>
            </view>
          </uv-form-item>
        </uv-form>
      </scroll-view>

      <view class="py-12 hair-t">
        <uv-button text="保存" type="primary" @click="save" />
      </view>
    </view>

    <uv-picker
      ref="pickerRef"
      key-name="name"
      :columns="areaColumns"
      @cancel="updateAreaShow(false)"
      @confirm="areaConfirm"
      @change="areaChange"
    />
  </uv-popup>
</template>

<script setup>
import {
  ref,
  watch,
  defineProps,
  defineEmits
} from 'vue'

import $ from '@/sheep'

const props = defineProps({
  show: Boolean,
  data: {
    type: Object,
    default: () => {}
  }
})
const emit = defineEmits(['update:show', 'done'])

const formRef = ref(null)
const popupRef = ref(null)
const pickerRef = ref(null)
const areaColumns = ref([])

watch(() => props.show, val => {
  if (val)
    open()
	 else
    close()
})

const {
  form,
  assignForm
} = $.useForm({
  id: undefined,
  name: '',
  phone: '',
  address: '',
  is_def: 0,
  province_id: 0,
  province_name: '',
  city_id: 0,
  city_name: '',
  district_id: 0,
  district_name: ''
})

const rules = {
  name: [{
    required: true,
    message: '请输入收货人姓名'
  }],
  phone: [{
    required: true,
    message: '请输入手机号'
  },
  {
    pattern: /^1\d{10}$/,
    message: '请输入正确的手机号'
  }
  ],
  area_code: [{
    required: true,
    message: '请选择省市区'
  }],
  address: [{
    required: true,
    message: '请输入详细地址'
  }]
}

function getList() {
  $.get('/index/areaList').then(res => {
    const areaList = $.utils.toTree(res.data)
    areaColumns.value = [areaList, areaList[0].children, areaList[0].children[0].children]
  })
}

function save() {
  formRef.value.validate().then(res => {
    $.post('/user/addressEdit', form).then(res => {
      if (res.success) {
        close()
        emit('done')
      }
      $.utils.toast('操作成功')
    })
  }).catch(err => {
    console.log(err)
  })
}

function updateAreaShow(value) {
  if (value)
    pickerRef.value.open()
  else
    pickerRef.value.close()
}

function open() {
  if (!areaColumns.value.length) {
    getList()
  }
  assignForm(props.data)
  popupRef.value.open()
}

function close() {
  popupRef.value.close()
}

function areaChange({
  columnIndex,
  index
}) {
  // 当第一列值发生变化时，变化第二列(后一列)对应的选项
  const data = areaColumns.value[columnIndex][index].children
  if (columnIndex === 0) {
    areaColumns.value[1] = data
    areaColumns.value[2] = data[0].children

    pickerRef.value.setColumnValues(1, data)
    pickerRef.value.setColumnValues(2, data[0].children)
  } else if (columnIndex === 1) {
    areaColumns.value[2] = data
    pickerRef.value.setColumnValues(2, data)
  }
}

function areaConfirm({ value }) {
  form.province_id = value[0].id
  form.province_name = value[0].name
  form.city_id = value[1].id
  form.city_name = value[1].name
  form.district_id = value[2].id
  form.district_name = value[2].name

  updateAreaShow(false)
}
</script>

<style lang="scss">
	.popup {
		width: 620rpx;
		padding: 0 30rpx;
	}
</style>
